package com.ihrm.company.controller;

import com.ihrm.common.controller.BaseController;
import com.ihrm.common.entity.Result;
import com.ihrm.common.entity.ResultCode;
import com.ihrm.company.service.api.CompanyService;
import com.ihrm.company.service.api.DepartmentService;
import com.ihrm.domain.company.Company;
import com.ihrm.domain.company.Department;
import com.ihrm.domain.company.response.DeptListResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author chentao
 * 解决跨域问题
 */
@CrossOrigin
@RestController
@RequestMapping(value = "/company")
public class DepartmentController extends BaseController {

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private CompanyService companyService;


    /**
     * 保存部门
     */
    @RequestMapping(value = "/department", method = RequestMethod.POST)
    public Result save(@RequestBody Department department) {
        //设置保存的企业id
        department.setCompanyId(companyId);
        departmentService.add(department);
        return new Result(ResultCode.SUCCESS);
    }


    /**
     * 根据企业id查询部门列表
     */
    @RequestMapping(value = "/department", method = RequestMethod.GET)
    public Result findAll() {


        //制定企业id
        Company company = companyService.findById(companyId);
        System.out.println(company);
        //完成查询
        List<Department> list = departmentService.findAll(companyId);

        //构造返回结果
        DeptListResult deptListResult = new DeptListResult(company, list);

        return new Result(ResultCode.SUCCESS, deptListResult);
    }


    /**
     * 根据id查询单个部门
     */
    @RequestMapping(value = "/department/{id}", method = RequestMethod.GET)
    public Result findById(@PathVariable(value = "id") String id) {
        Department byId = departmentService.findById(id);
        return new Result(ResultCode.SUCCESS, byId);
    }


    /**
     * 更新部门
     */
    @RequestMapping(value = "/department", method = RequestMethod.PUT)
    public Result update(@RequestBody Department department) {
        //完成更新
        departmentService.update(department);
        return new Result(ResultCode.SUCCESS);
    }


    /**
     * 根据id删除部门
     */
    @RequestMapping(value = "/department/{id}", method = RequestMethod.DELETE)
    public Result delete(@PathVariable(value = "id") String id) {
        departmentService.deleteById(id);
        return new Result(ResultCode.SUCCESS);
    }


    @RequestMapping(value="/department/search",method = RequestMethod.POST)
    public Department findByCode(@RequestParam(value="code") String code, @RequestParam(value="companyId") String companyId){
        return departmentService.findByCode(code, companyId);
    }

}
